package cai.a.viewpager4;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现步骤：
 *  一，activity_main中来个ViewPager控件
 *  二，代码来三个Fragment(这里统一用v4包中的Fragment，以免报错)，并且用集合封装下下
 *  三,继承FragmentPagerAdapter,覆盖两个方法，还有一个构造方法
 */
public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private List<Fragment> mFragmentList;
    private MyFragmentPagerAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mFragmentList = new ArrayList<Fragment>();
        mFragmentList.add(new Fragment1());
        mFragmentList.add(new Fragment2());
        mFragmentList.add(new Fragment3());

        /**getFragmentManager和getSupportFragentManager方法的区别*/
        /**Activity中只有getFragmentManager，这里要继承AppCompatActivity或者FragmentActivity，通过getSupportFragmentManager获取FragmentManager*/
        /**因为构造方法中super(fm)需要传入v4包中FragmentManager*/
        mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), (ArrayList<Fragment>) mFragmentList);
        mViewPager.setAdapter(mAdapter);

    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragments;

        /**super(fm)传递的是v4包里的FragmentManager，因此构造方法这里传递必须是v4包里面的FragmentManager */
        public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        /**返回当前Fragment*/
        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return fragments.get(position);
        }

        /**Fragment的数量*/
        @Override
        public int getCount() {
            return fragments.size();
        }
    }
}
